package cn.edu.ctbu.sbadmin.system.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;

public class UserModularRealmAuthenticator extends ModularRealmAuthenticator {
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken)
        throws AuthenticationException{
        assertRealmsConfigured();
        UserToken userToken = (UserToken) authenticationToken;
        String loginType = userToken.getLoginType();
        Collection<Realm> realms = getRealms();

        Collection<Realm> loginTypeRealms = new ArrayList<Realm>();
        for(Realm realm:realms){
            if(realm.getName().contains(loginType)){
                loginTypeRealms.add(realm);
            }
        }
        if (loginTypeRealms.size() == 1){
            System.out.println("doSingleRealmAuthentication() 执行");
            return doSingleRealmAuthentication(loginTypeRealms.iterator().next(),userToken);
        }else {
            System.out.println("doMultiRealmAuthentication() 执行");
            return doMultiRealmAuthentication(loginTypeRealms,userToken);
        }
    }

}
